// pages/login/login.js
const app = getApp();

Page({
  data: {
    passwordVisible: false,
    phone: '',
    password: '',
    loading: false,
    agreedToPolicy: false, // 隐私政策同意状态
    showAgreementModal: false, // 用户服务协议弹窗
    showPrivacyModal: false, // 隐私政策弹窗
    showRegisterModal: false, // 注册弹窗
    registerPhone: '',
    registerPassword: '',
    registerConfirmPassword: '',
    registerPasswordVisible: false,
    registerConfirmPasswordVisible: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},

  /**
   * 切换隐私政策同意状态
   */
  toggleAgreement() {
    this.setData({ 
      agreedToPolicy: !this.data.agreedToPolicy 
    })
  },

  /**
   * 查看用户服务协议
   */
  viewUserAgreement() {
    console.log('点击了用户服务协议')
    this.setData({
      showAgreementModal: true
    })
    console.log('showAgreementModal:', this.data.showAgreementModal)
  },

  /**
   * 查看隐私政策
   */
  viewPrivacyPolicy() {
    console.log('点击了隐私政策')
    this.setData({
      showPrivacyModal: true
    })
    console.log('showPrivacyModal:', this.data.showPrivacyModal)
  },

  /**
   * 关闭弹窗
   */
  closeModal() {
    this.setData({
      showAgreementModal: false,
      showPrivacyModal: false,
      showRegisterModal: false
    })
  },

  /**
   * 打开注册弹窗
   */
  onRegister() {
    this.setData({ showRegisterModal: true });
  },

  /**
   * 阻止事件冒泡
   */
  stopPropagation() {
    // 阻止冒泡
  },

  /**
   * 阻止滚动穿透
   */
  preventTouchMove() {
    // 仅阻止事件冒泡
  },

  onTogglePassword() {
    this.setData({ passwordVisible: !this.data.passwordVisible });
  },

  onInputPhone(e) {
    this.setData({ phone: e.detail.value.trim() })
  },

  onInputPassword(e) {
    this.setData({ password: e.detail.value })
  },

  async onSubmit() {
    if (this.data.loading) return;
    
    // 检查是否同意隐私政策
    if (!this.data.agreedToPolicy) {
      wx.showToast({ 
        title: '请先阅读并同意用户协议和隐私政策', 
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    const { phone, password } = this.data
    if (!phone || !password) {
      wx.showToast({ title: '请输入账号和密码', icon: 'none' })
      return
    }
    this.setData({ loading: true })
    try {
      const res = await app.request({
        url: '/api/auth/login',
        method: 'POST',
        data: { phone, password }
      })
      if (res.statusCode === 200 && res.data && res.data.success && res.data.data && res.data.data.token) {
        wx.setStorageSync('token', res.data.data.token)
        wx.showToast({ title: '登录成功', icon: 'none' })
        setTimeout(() => {
          wx.reLaunch({ url: '/pages/user/user' })
        }, 600)
      } else {
        wx.showToast({ title: res.data?.message || '登录失败', icon: 'none' })
      }
    } catch (e) {
      wx.showToast({ title: '网络错误', icon: 'none' })
    } finally {
      this.setData({ loading: false })
    }
  },

  async onConfirmRegister() {
    if (this.data.loading) return;

    const { registerPhone, registerPassword, registerConfirmPassword } = this.data;

    if (!registerPhone || !registerPassword || !registerConfirmPassword) {
      wx.showToast({ title: '请填写所有字段', icon: 'none' });
      return;
    }

    if (registerPassword !== registerConfirmPassword) {
      wx.showToast({ title: '两次输入的密码不一致', icon: 'none' });
      return;
    }

    this.setData({ loading: true });

    try {
      const res = await app.request({
        url: '/api/auth/register',
        method: 'POST',
        data: { 
          phone: registerPhone, 
          password: registerPassword 
        }
      });

      if (res.data && res.data.success && res.data.data.token) {
        wx.setStorageSync('token', res.data.data.token);
        wx.showToast({ title: '注册成功，已自动登录', icon: 'none' });
        this.setData({ showRegisterModal: false });
        setTimeout(() => {
          wx.reLaunch({ url: '/pages/user/user' });
        }, 600);
      } else {
        wx.showToast({ title: res.data?.message || '注册失败', icon: 'none' });
      }
    } catch (e) {
      wx.showToast({ title: '网络错误', icon: 'none' });
    } finally {
      this.setData({ loading: false });
    }
  },

  onInputRegisterPhone(e) {
    this.setData({ registerPhone: e.detail.value.trim() });
  },

  onInputRegisterPassword(e) {
    this.setData({ registerPassword: e.detail.value });
  },

  onInputRegisterConfirmPassword(e) {
    this.setData({ registerConfirmPassword: e.detail.value });
  }
});